//
//  MyMessageViewController.m
//  eshow
//
//  Created by Hisoka on 15/12/11.
//  Copyright © 2015年 Hisoka. All rights reserved.
//

#import "MyMessageViewController.h"
#import "MyMessageTableViewCell.h"
#import "MyMessageDetailViewController.h"

static NSString * const MESSAGE_CELL = @"messageCell";

@interface MyMessageViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *mySMSTV;
@property (nonatomic, strong) NSMutableArray *mySMSData;
@property (nonatomic, strong) NSString *hasMoreData;
@property (nonatomic, strong) NSString *nextPageNum;
@property (nonatomic, strong) UIView *tableBgV;

@end

@implementation MyMessageViewController

- (void) viewWillDisappear:(BOOL)animated {
    [MobClick event:@"Click_MyMessage_backBTN"];

    [SVProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self customizeBackItem];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setStyle];
    [self refresh];
}

#pragma mark - 请求消息列表
- (void) getSMSList:(NSString *) pageNum {
    
    [SVProgressHUD show];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[NSString stringWithFormat:@"%@", [[TMCache sharedCache] objectForKey:@"SSID"]] forKey:@"ssid"];
    [parameters setObject:pageNum forKey:@"p"];
    [parameters setObject:@"15" forKey:@"psize"];
    
    [[HttpManager instance] requestWithMethod:@"User/getSMSList"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          NSDictionary *dataTmp = [result objectForKey:@"data"];
                                          
                                          if ([[dataTmp objectForKey:@"sms_list"] count] <= 0) {
//                                              [self setEmptyStyle];
                                              _mySMSTV.backgroundView.hidden = NO;
                                          }else{
                                              if ([pageNum isEqualToString:@"1"]) {
                                                  _mySMSData = [[NSMutableArray alloc] initWithArray:[dataTmp objectForKey:@"sms_list"]];
                                              }else{
                                                  [_mySMSData addObjectsFromArray:[dataTmp objectForKey:@"sms_list"]];
                                              }
                                              
                                              _hasMoreData = [dataTmp objectForKey:@"hasMore"];
                                              _nextPageNum = [dataTmp objectForKey:@"nextPageNum"];
                                              
                                              [_mySMSTV reloadData];
                                              _mySMSTV.backgroundView.hidden = YES;
                                          }
                                          
                                          [_mySMSTV.mj_header endRefreshing];
                                          
                                          [SVProgressHUD dismiss];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

#pragma mark - 标记已读消息
- (void) setReadSMS:(NSString *)pid {
    [SVProgressHUD show];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[NSString stringWithFormat:@"%@", [[TMCache sharedCache] objectForKey:@"SSID"]] forKey:@"ssid"];
    [parameters setObject:pid forKey:@"pid"];
    
    [[HttpManager instance] requestWithMethod:@"User/setReadSMS"
                                   parameters:parameters
                                      success:^(NSDictionary *result) {
                                          NSDictionary *userInfoTmp = [result objectForKey:@"data"];
                                          [[TMCache sharedCache] setObject:userInfoTmp forKey:@"userInfo"];
                                      }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                          [SVProgressHUD showInfoWithStatus:[error localizedDescription] maskType:SVProgressHUDMaskTypeBlack];
                                      }];
}

- (void) refresh {
    _mySMSTV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getSMSList:@"1"];
    }];
    [_mySMSTV.mj_header beginRefreshing];
}

- (void) setStyle {
    self.navigationItem.title = @"消息";
    self.view.backgroundColor = GRAY_COLOR;
    
    self.mySMSTV = [UITableView newAutoLayoutView];
    [self.view addSubview:_mySMSTV];
    
    [_mySMSTV autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [_mySMSTV autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.view];
    [_mySMSTV autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self.view];
    [_mySMSTV autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.view];
    
    _mySMSTV.delegate = self;
    _mySMSTV.dataSource = self;
    _mySMSTV.separatorStyle = UITableViewCellAccessoryNone;
    
    [_mySMSTV registerClass:[MyMessageTableViewCell class] forCellReuseIdentifier:MESSAGE_CELL];
    
    self.nextPageNum = @"1";
    self.hasMoreData = @"0";
    
    self.tableBgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    UILabel *emptyLB = [UILabel newAutoLayoutView];
    [_tableBgV addSubview:emptyLB];
    
    [emptyLB autoAlignAxis:ALAxisHorizontal toSameAxisOfView:_tableBgV];
    [emptyLB autoAlignAxis:ALAxisVertical toSameAxisOfView:_tableBgV];
    [emptyLB autoSetDimensionsToSize:CGSizeMake(ScreenWidth, 50)];
    emptyLB.textAlignment = NSTextAlignmentCenter;
    emptyLB.backgroundColor = [UIColor clearColor];
    emptyLB.textColor = GRAY_COLOR;
    emptyLB.text = TEXT_EMPTY_DATA;
    
    _mySMSTV.backgroundView = _tableBgV;
    _mySMSTV.backgroundView.hidden = YES;
    
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([_mySMSData count] <= 0) {
        return 0;
    }else{
        return [_mySMSData count];
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MESSAGE_CELL forIndexPath:indexPath];
    
    cell.titleLB.text = [[_mySMSData objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.dateLB.text = [[_mySMSData objectAtIndex:indexPath.row] objectForKey:@"created_time"];

    if ([[[_mySMSData objectAtIndex:indexPath.row] objectForKey:@"is_read"] isEqualToString:@"0"]) {
        cell.readLB.hidden = NO;
    }else{
        cell.readLB.hidden = YES;
    }
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self setReadSMS:[[_mySMSData objectAtIndex:indexPath.row] objectForKey:@"id"]];
    
    MyMessageTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    cell.readLB.hidden = YES;
    
    MyMessageDetailViewController *detail = [[MyMessageDetailViewController alloc] init];

    NSDictionary *tmpDic = [_mySMSData objectAtIndex:indexPath.row];
    
    if ([[tmpDic objectForKey:@"is_web"] isEqualToString:@"1"]) {
        detail.reqUrl = [tmpDic objectForKey:@"url"];
    }else{
        detail.contentStr = [tmpDic objectForKey:@"content"];
    }
    
    detail.titleStr = [tmpDic objectForKey:@"title"];
    detail.isWebView = [tmpDic objectForKey:@"is_web"];
    
    [self.navigationController pushViewController:detail animated:YES];
}

- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _mySMSTV.scrollEnabled = NO;
    if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
        [_mySMSTV.mj_footer beginRefreshing];
        
        if ([_hasMoreData isEqualToString:@"1"]) {
            _mySMSTV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                if (![_nextPageNum isEqualToString:@"1"]) {
                    [self getSMSList:_nextPageNum];
                }else{
                    [_mySMSTV.mj_footer endRefreshingWithNoMoreData];
                }
            }];
        }else{
            [_mySMSTV.mj_footer endRefreshingWithNoMoreData];
        }
    }
    _mySMSTV.scrollEnabled = YES;
}

#pragma mark - 设置空信息样式
- (void) setEmptyStyle {
    UILabel *defaultLB = [UILabel newAutoLayoutView];
    [self.view addSubview:defaultLB];
    
    [defaultLB autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.view];
    [defaultLB autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [defaultLB autoSetDimensionsToSize:CGSizeMake(150, 30)];
    defaultLB.backgroundColor = [UIColor clearColor];
    defaultLB.textAlignment = NSTextAlignmentCenter;
    defaultLB.text = @"暂无相关内容";
    defaultLB.textColor = [UIColor grayColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
